package com.slm.krstartimes.activity;


import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.slm.krstartimes.R;
import com.slm.krstartimes.db.sqlite.SQLiteDataBaseManager;
import com.slm.krstartimes.utils.News;
import com.slm.krstartimes.utils.RoundImageView;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners;
import com.umeng.socialize.exception.SocializeException;
import com.umeng.socialize.sso.UMQQSsoHandler;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Set;


/**
 * Created by dllo on 15/8/7.
 */
public class PersonCenterActivity extends ActionBarActivity implements GestureDetector.OnGestureListener, View.OnTouchListener, View.OnClickListener {
    //    //服务器地址
    //    private static final String Host = "http://192.168.1.105:8080/ImageServer/upServer";
    /* 头像文件 */
    private static final String IMAGE_FILE_NAME = "temp_head_image.jpg";
    /* 请求识别码 */
    private static final int CODE_GALLERY_REQUEST = 0xa0;
    private static final int CODE_CAMERA_REQUEST = 0xa1;
    private static final int CODE_RESULT_REQUEST = 0xa2;
    // 裁剪后图片的宽(X)和高(Y),480 X 480的正方形。
    private static int output_X = 480;
    private static int output_Y = 480;
    Intent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    UMSocialService mController = UMServiceFactory.getUMSocialService("com.umeng.login");
    private GestureDetector mGestureDetector;
    private int verticalMinDistance = 30;
    private int middleDistance = 150;
    private int minVelocity = 0;
    private LinearLayout center_layout;
    //多线程通信
    private PopupWindow popupWindow;
    private Context mContext;
    // 上传的bitmap
    private Bitmap upbitmap;
    // 记录文件名
    private String filename;
    private Handler myHandler;
    private ProgressDialog myDialog;
    private TableRow myCollect, update, aboutus;
    private TextView userNameTv;
    private Button outLoginBt;
    private RequestQueue queue;
    private TextView login;
    private TextView loginout;
    private com.nostra13.universalimageloader.core.ImageLoader myImageLoader;
    private DisplayImageOptions options = null;
    private RequestQueue requestQueue;
    private RoundImageView cover_user_photo;
    private SharedPreferences preferences;
    private SharedPreferences.Editor editor;
    private Map<String, Object> info;

    /**
     * 判断SDCard是否可用
     *
     * @return
     */
    public static boolean isSDCardEnable() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.person_center);
        preferences = getSharedPreferences("haveLogin", Context.MODE_PRIVATE);
        //获取imageLoader的实例
        myImageLoader = com.nostra13.universalimageloader.core.ImageLoader.getInstance();
        //初始化imageloader
        myImageLoader.init(ImageLoaderConfiguration.createDefault(this));

        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.mipmap.load)
                .showImageOnFail(R.mipmap.load)
                .displayer(new RoundedBitmapDisplayer(10))//设置圆角图片
                .cacheInMemory(true)
                .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)//设置按比例缩放
                .cacheOnDisc()
                        //.discCache(new UnlimitedDiscCache(cacheDir))
                .build();

        initView();

        List<News> log = MainActivity.sqLiteDataBaseTools.query(SQLiteDataBaseManager.LOG);
        if (log.size() > 0) {
            login.setText(log.get(0).getTitle());
            myImageLoader.displayImage(log.get(0).getImage(), cover_user_photo, options);
        }
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.upload_header_picture, null);
        LinearLayout cameraLl = (LinearLayout) view.findViewById(R.id.cameraLl);
        LinearLayout pictureLl = (LinearLayout) view.findViewById(R.id.pictureLl);

        // 引入窗口配置文件
        cameraLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                choseHeadImageFromCameraCapture();

            }
        });
        pictureLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                choseHeadImageFromGallery();
            }
        });

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.id.cover_user_photo);
        //        Bitmap output = toRoundCorner(bitmap, 15.0f);
        //        cover_user_photo.setImageBitmap(output);
        // 创建PopupWindow对象
        final PopupWindow pop = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, false);

        //        popupWindow.setContentView(menuView);//设置包含视图
        //        popupWindow.setWidth()
        //        popupWindow.setHeight(int )//设置弹出框大小
        //
        //        //设置进场动画
        //        popupWindow.setAnimationStyle(R.style.AnimationPreview);//设置动画样式

        pop.setBackgroundDrawable(new BitmapDrawable());// 需要设置一下此参数，点击外边可消失

        pop.setOutsideTouchable(true);//设置点击窗口外边窗口消失

        pop.setFocusable(true);// 设置此参数获得焦点，否则无法点击
        cover_user_photo.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                if (pop.isShowing()) {
                    // 隐藏窗口，如果设置了点击窗口外小时即不需要此方式隐藏
                    pop.dismiss();
                } else {
                    // 显示窗口
                    pop.showAsDropDown(view);
                }

            }
        });

    }

    /**
     * 初始化
     */
    private void initView() {
        center_layout = (LinearLayout) findViewById(R.id.center_layout);

        cover_user_photo = (RoundImageView) findViewById(R.id.cover_user_photo);
        update = (TableRow) findViewById(R.id.update);
        myCollect = (TableRow) findViewById(R.id.myCollect);
        aboutus = (TableRow) findViewById(R.id.aboutus);
        userNameTv = (TextView) findViewById(R.id.userNameTv);

        mGestureDetector = new GestureDetector(this);
        center_layout.setOnTouchListener(this);
        mContext = this;
        center_layout.setLongClickable(true);
        myCollect.setOnClickListener(this);
        login = (TextView) findViewById(R.id.login);
        login.setOnClickListener(this);
        loginout = (TextView) findViewById(R.id.loginout);
        loginout.setOnClickListener(this);
        update.setOnClickListener(this);
        aboutus.setOnClickListener(this);
    }


    /**
     * 本地获取图片
     */
    private void choseHeadImageFromGallery() {
        Intent intentFromGallery = new Intent();
        // 设置文件类型
        intentFromGallery.setType("image/*");
        intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intentFromGallery, CODE_GALLERY_REQUEST);
    }

    /**
     * 调用相机
     */
    private void choseHeadImageFromCameraCapture() {
        // 指定调用相机拍照后照片的储存路径
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment
                .getExternalStorageDirectory(),
                "xiaoma.jpg")));
        startActivityForResult(intent, CODE_CAMERA_REQUEST);
    }

    /**
     * 裁剪图片
     *
     * @param bitmap
     * @param v
     * @return
     */


    /**
     * 新的Activity关闭后会向前面的Activity传回数据，为了得到传回的数据，
     * 必须在前面的Activity中重写onActivityResult
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent data) {
        switch (requestCode) {
            case CODE_GALLERY_REQUEST://直接从相册获取

                try {
                    cropRawPhoto(data.getData());
                } catch (NullPointerException e) {
                    e.printStackTrace();

                }
                break;

            case CODE_CAMERA_REQUEST://调用相机拍照
                if (isSDCardEnable()) {
                    File tempFile = new File(
                            Environment.getExternalStorageDirectory(),
                            "/xiaoma.jpg");
                    cropRawPhoto(Uri.fromFile(tempFile));
                } else {
                    Toast.makeText(getApplication(), "没有SDCard!", Toast.LENGTH_LONG)
                            .show();
                }

                break;

            case CODE_RESULT_REQUEST://取得裁剪之后的照片
                if (data != null) {
                    setPicToView(data);
                }

                break;

            default:
                break;

        }

        super.onActivityResult(requestCode, resultCode, data);

    }

    /**
     * 裁剪原始的图片
     */
    public void cropRawPhoto(Uri uri) {

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");

        // 设置裁剪
        intent.putExtra("crop", "true");

        // aspectX , aspectY :宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        // outputX , outputY : 裁剪图片宽高
        intent.putExtra("outputX", output_X);
        intent.putExtra("outputY", output_Y);
        intent.putExtra("return-data", true);

        startActivityForResult(intent, CODE_RESULT_REQUEST);
    }

    /**
     * 保存裁剪之后的图片数据
     *
     * @param picdata
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void setPicToView(Intent picdata) {
        Bundle extras = picdata.getExtras();
        if (extras != null) {
            // 取得SDCard图片路径做显示
            Bitmap photo = extras.getParcelable("data");
            Drawable drawable = new BitmapDrawable(photo);
            cover_user_photo.setImageDrawable(drawable);

        }
    }


    @Override
    public boolean onDown(MotionEvent motionEvent) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent motionEvent) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent motionEvent) {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent motionEvent) {

    }

    /**
     * 滑动返回
     *
     * @param e1
     * @param e2
     * @param v
     * @param v1
     * @return
     */
    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float v, float v1) {
        if (e2.getX() - e1.getX() > verticalMinDistance && Math.abs(v) > minVelocity && (Math.abs(e2.getY() - e1.getY()) < middleDistance)) {
            finish();
        } else if (e1.getX() - e2.getX() > verticalMinDistance && Math.abs(v) > minVelocity && (Math.abs(e2.getY() - e1.getY()) < middleDistance)) {
            Toast.makeText(PersonCenterActivity.this, "左滑", Toast.LENGTH_SHORT).show();
        }
        return false;
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        return mGestureDetector.onTouchEvent(motionEvent);
    }

    /**
     * 选项监听
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        List<News> log = MainActivity.sqLiteDataBaseTools.query(SQLiteDataBaseManager.LOG);
        switch (view.getId()) {

            case R.id.collection:
                if (log.size() > 0) {
                    Intent collect = new Intent(PersonCenterActivity.this, CollectActivity.class);
                    startActivity(collect);
                } else {
                    Toast.makeText(PersonCenterActivity.this, "请先登录", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.system_message:
                if (log.size() > 0) {
                    Intent collect = new Intent(PersonCenterActivity.this, CollectActivity.class);
                    startActivity(collect);
                } else {
                    Toast.makeText(PersonCenterActivity.this, "请先登录", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.general_setting:
                if (log.size() > 0) {
                    Intent collect = new Intent(PersonCenterActivity.this, CollectActivity.class);
                    startActivity(collect);
                } else {
                    Toast.makeText(PersonCenterActivity.this, "请先登录", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.feedback:
                if (log.size() > 0) {
                    Intent collect = new Intent(PersonCenterActivity.this, CollectActivity.class);
                    startActivity(collect);
                } else {
                    Toast.makeText(PersonCenterActivity.this, "请先登录", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.aboutus:
                Intent intent = new Intent(PersonCenterActivity.this, AboutusActivity.class);
                startActivity(intent);
                break;
            case R.id.update:
                checkUpdate();
                break;
            case R.id.myCollect:
                if (log.size() > 0) {
                    Intent collect1 = new Intent(PersonCenterActivity.this, CollectActivity.class);
                    startActivity(collect1);
                } else {
                    Toast.makeText(PersonCenterActivity.this, "请先登录", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.loginout:
                cover_user_photo.setImageResource(R.mipmap.appic);
                login.setText("立即登录");
                MainActivity.sqLiteDataBaseTools.delete(SQLiteDataBaseManager.LOG);
                break;
            case R.id.login:
                //参数1为当前Activity， 参数2为开发者在QQ互联申请的APP ID，参数3为开发者在QQ互联申请的APP kEY.
                UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(PersonCenterActivity.this, "100424468",
                        "c7394704798a158208a74ab60104f0ba");
                qqSsoHandler.addToSocialSDK();


                mController.doOauthVerify(PersonCenterActivity.this, SHARE_MEDIA.SINA, new SocializeListeners.UMAuthListener() {
                    ImageLoader imageLoader = new ImageLoader(queue, new ImageLoader.ImageCache() {
                        @Override
                        public Bitmap getBitmap(String s) {
                            return null;
                        }

                        @Override
                        public void putBitmap(String s, Bitmap bitmap) {

                        }
                    });

                    @Override
                    public void onStart(SHARE_MEDIA platform) {
                        Toast.makeText(PersonCenterActivity.this, "授权开始", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onError(SocializeException e, SHARE_MEDIA platform) {
                        Toast.makeText(PersonCenterActivity.this, "授权错误", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete(Bundle value, SHARE_MEDIA platform) {
                        Toast.makeText(PersonCenterActivity.this, "授权完成", Toast.LENGTH_SHORT).show();
                        editor = preferences.edit();
                        editor.putBoolean("firstStart", false);
                        editor.commit();
                        //获取相关授权信息
                        mController.getPlatformInfo(PersonCenterActivity.this, SHARE_MEDIA.SINA, new SocializeListeners.UMDataListener() {
                            @Override
                            public void onStart() {
                                Toast.makeText(PersonCenterActivity.this, "获取平台数据开始...", Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onComplete(int status, Map<String, Object> info) {

                                if (status == 200 && info != null) {
                                    StringBuilder sb = new StringBuilder();
                                    Set<String> keys = info.keySet();
                                    for (String key : keys) {
                                        sb.append(key + "=" + info.get(key).toString() + "\r\n");
                                    }
                                    Log.d("TestData", sb.toString());
                                    // 隐藏登录按钮
                                    // 设置用户名可见
                                    userNameTv.setVisibility(View.VISIBLE);
                                    login.setText((String) info.get("screen_name"));
                                    myImageLoader.displayImage(info.get("profile_image_url").toString(), cover_user_photo, options);
                                    MainActivity.sqLiteDataBaseTools.insert("", info.get("screen_name").toString(), info.get("profile_image_url").toString(), "", "", SQLiteDataBaseManager.LOG);
                                } else {
                                    Log.d("TestData", "发生错误：" + status);
                                }
                            }
                        });


                    }

                    @Override
                    public void onCancel(SHARE_MEDIA platform) {
                        Toast.makeText(PersonCenterActivity.this, "授权取消", Toast.LENGTH_SHORT).show();
                    }
                });


                break;

        }
    }

    /**
     * 检查更新
     */
    private void checkUpdate() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setNegativeButton(R.string.after_ask, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        builder.setPositiveButton(R.string.update_now, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toast.makeText(PersonCenterActivity.this, "服务器开了小差,稍后再试", Toast.LENGTH_SHORT).show();
            }
        });
        builder.setItems(R.array.update_information, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }

}
